package com.xju.atpgs.controller;

import com.xju.atpgs.entity.Exam;
import com.xju.atpgs.entity.ExamRequest;
import com.xju.atpgs.entity.Question;
import com.xju.atpgs.entity.ResultExam;
import com.xju.atpgs.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/exam")
public class ExamController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private QuestionService questionService;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private SectionService sectionService;
    @Autowired
    private UserService userService;
    @Autowired
    private ExamService examService;

    @RequestMapping("/autogenerator")
    @ResponseBody
    public Object autoGenerator(@RequestBody ExamRequest examRequest) {
        String testPaperPath = null;
        try {
            testPaperPath = examService.autoGenerator(examRequest);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        map.put("paperPath", testPaperPath);
        return map;
    }

    @RequestMapping("download_paper")
    public void downloadPaper(HttpServletRequest request, HttpServletResponse response, String path) {
        File file = new File(path);
        String filename = file.getName();
        if (file.exists()) { //判断文件父目录是否存在
//            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
             response.setContentType("application/force-download");
            try {
                response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(filename, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/manual-generator")
    public String manualGenerator(Model model){
        List<Question> choice=questionService.findByType("选择题");
        List<Question> judge=questionService.findByType("判断题");
        List<Question> filling=questionService.findByType("填空题");
        List<Question> shortAnwser=questionService.findByType("简答题");
        List<Question> solve=questionService.findByType("应用题");
        model.addAttribute("choice",choice);
        model.addAttribute("judge",judge);
        model.addAttribute("filling",filling);
        model.addAttribute("shortAnwser",shortAnwser);
        model.addAttribute("solve",solve);
        return "module_three/exam_generator_manual";
    }

    @RequestMapping("/manual-generator-request")
    @ResponseBody
    public Object paperGenerator(@RequestBody String[] data){
        int i=data.length;
        String name=data[i-1];
        String choice=data[i-2];
        String judge=data[i-3];
        String filling=data[i-4];
        String shortAnswer=data[i-5];
        String solve=data[i-6];
        String choiceScore=data[i-7];
        String judgeScore=data[i-8];
        String fillingScore=data[i-9];
        String shortAnswerScore=data[i-10];
        String solveScore=data[i-11];
        String[] newdata=new String[i-11];
        for(int j=0;j<i-11;j++){
            newdata[j]=data[j];
        }
        ExamRequest examRequest=new ExamRequest(name,choice,judge,filling,shortAnswer,solve,choiceScore,judgeScore,fillingScore,shortAnswerScore,solveScore,"0");
        String path=examService.manualGenerator(newdata,examRequest);
        Map<String,Object> map=new HashMap<>();
        map.put("success",true);
        map.put("path",path);
        return map;
    }

    @RequestMapping("/manager")
    public String manager(Model model){
        List<ResultExam> examList=examService.examManager();
        model.addAttribute("examList",examList);
        return "module_three/exam_manager";
    }
}
